from django.http import HttpResponse
from netmiko import ConnectHandler
import paramiko


# 添加ip白名单
def add_ip(squid_info, hosts, description):
    net_connect = ConnectHandler(**squid_info)
    print("已登录服务器：" + squid_info["host"])
    # 初始化命令列表
    commands = []
    # 循环读取逗号分割的host
    for host in hosts.split(","):
        commands.append('echo acl localnet src ' + host + '\ \ \ \ ' + '#' + description + ' >> /etc/squid/srcip.acl')
    commands.append('systemctl restart squid')
    print("执行命令如下：")
    # for command in commands:
    #     print(command)
    # 执行
    print(net_connect.find_prompt(), end=' ')
    result = net_connect.send_config_set(commands)
    print(result)

    # 关闭连接
    net_connect.disconnect()


# 添加ip白名单v2
def add_ip_v2(host, username, password, hosts, description):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(host, username=username, password=password)
        cmd = 'echo acl localnet src ' + hosts + '\ \ \ \ ' + '#' + description + ' >> /etc/squid/srcip.acl'
        ssh.exec_command(cmd)
    except:
        pass


# 删除ip白名单
def del_ip(squid_info, hosts):
    net_connect = ConnectHandler(**squid_info)
    print("已登录服务器：" + squid_info["host"])
    # 初始化命令列表
    commands = []
    # 循环读取逗号分割的host
    for host in hosts.split(","):
        commands.append("sed -i '/" + host + "/d' /etc/squid/ipacl.conf")
    commands.append('systemctl restart squid')
    print("执行命令如下：")
    # for command in commands:
    #     print(command)
    # 执行
    print(net_connect.find_prompt(), end=' ')
    result = net_connect.send_config_set(commands)
    print(result)

    # 关闭连接
    net_connect.disconnect()


# 添加域名白名单
def add_domain(squid_info, dstdomains):
    net_connect = ConnectHandler(**squid_info)
    print("已登录服务器：" + squid_info["host"])

    # 初始化命令列表
    commands = []
    # 循环读取逗号分割的host

    for dstdomain in dstdomains.split(","):
        commands.append('echo acl White_List dstdomain ' + dstdomain + ' >> /etc/squid/desdomain.acl')
    commands.append('systemctl restart squid')
    print("执行命令如下：")
    # for command in commands:
    #     print(command)
    # 执行
    print(net_connect.find_prompt(), end=' ')
    result = net_connect.send_config_set(commands)
    print(result)
    # 关闭连接
    net_connect.disconnect()


# 重启squid
def rssquid(host, username, password):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host, username=username, password=password)
    cmd = 'systemctl restart squid'
    ssh.exec_command(cmd)


def addip(hosts, description):
    add_ip_v2('172.20.68.9', 'root', '5Star.com', hosts, description)
    rssquid('172.20.68.9', 'root', '5Star.com')
    add_ip_v2('172.20.68.10', 'root', '5Star.com', hosts, description)
    rssquid('172.20.68.10', 'root', '5Star.com')
